import { DoubleArrow, toLineGeojson } from "./generate";

export const DrawDoubleArrow = {
	onSetup: () => {
		const clickCount = 0;

		return {
			coordinates: [],
			clickCount,
		};
	},
	onClick: function (state, e) {
		const { coordinates } = state;

		coordinates[state.clickCount] = [e.lngLat.lng, e.lngLat.lat];
		state.clickCount += 1;

		if (state.clickCount === 4) {
			this.map.fire("draw.create", {
				features: [state.feature.toGeoJSON()],
				mode: "double_arrow",
				controlPnts: state.coordinates,
			});
			this.changeMode("simple_select", {}, { silent: true });
		}
	},
	onMouseMove: function (state, e) {
		// console.log("onmousemove--state", state);
		const { clickCount, coordinates } = state;

		if (clickCount > 1) {
			coordinates[clickCount] = [e.lngLat.lng, e.lngLat.lat];
		}

		this.updateFeature(state);
	},

	toDisplayFeatures: (state, geojson, display) => {
		display(geojson);
	},

	updateFeature: function (state) {
		const { coordinates, feature } = state;
		if (coordinates.length < 3) return;

		const coords = DoubleArrow.generate(coordinates);
		const arrowFeat = toLineGeojson(coords);

		if (feature) {
			feature.setCoordinates(arrowFeat.geometry.coordinates);
		} else {
			const feat = this.newFeature(arrowFeat);
			this.addFeature(feat);

			state.feature = feat;
		}
	},
};
